﻿using System;
using System.IO;
using EFCachingProvider;
using EFCachingProvider.Caching;
using EFProviderWrapperToolkit;
using EFTracingProvider;

using log4net;
using log4net.Config;



namespace Query
{
    public partial class ExtendedExtRatesEntities : ExtRatesEntities
    {
        private ILog logOutput;
        private static readonly ILog Log4net = LogManager.GetLogger(typeof(GetFromDBService));

        public ExtendedExtRatesEntities()
            : this("name=ExtRatesEntities")
        {
        }
        public ExtendedExtRatesEntities(string connectionString)
            : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
                    connectionString,
                    "EFTracingProvider",
                    "EFCachingProvider"
            ))
        {
        }


        private EFTracingConnection TracingConnection
        {
            get { return this.UnwrapConnection<EFTracingConnection>(); }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandExecuting
        {
            add { this.TracingConnection.CommandExecuting += value; }
            remove { this.TracingConnection.CommandExecuting -= value; }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandFinished
        {
            add { this.TracingConnection.CommandFinished += value; }
            remove { this.TracingConnection.CommandFinished -= value; }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandFailed
        {
            add { this.TracingConnection.CommandFailed += value; }
            remove { this.TracingConnection.CommandFailed -= value; }
        }

        private void AppendToLog(object sender, CommandExecutionEventArgs e)
        {
            if (this.logOutput != null)
            {
                log4net.Config.DOMConfigurator.Configure();
                Log4net.Info(e.ToTraceString().TrimEnd());
                /*
                this.logOutput.WriteLine(e.ToTraceString().TrimEnd());
                this.logOutput.WriteLine();*/
            }
        }
        public ILog Log
        {
            get { return this.logOutput; }
            set
            {
                log4net.Config.DOMConfigurator.Configure();

                if ((this.logOutput != null) != (value != null))
                {
                    if (value == null)
                    {
                        CommandExecuting -= AppendToLog;
                    }
                    else
                    {
                        CommandExecuting += AppendToLog;
                    }
                }

                
                Log4net.Info("Entering application.");

                
                this.logOutput = value;
            }
        }

    }

}
